var module = angular.module('app.OrderController', []);

module.controller('OrderController',function ($scope, ConfigModule, $http, $location) {
    //$location.path('/order/index');
    $scope.$emit('hideNav',false);

});

module.controller('OrderIndexController',function ($scope, API, $stateParams) {
    $scope.$emit('hideNav',false);
    switch ($stateParams.status){
        case '0':
            $scope.status0 = 'active';
            break;
        case '1':
            $scope.status1 = 'active';
            break;
        case '2':
            $scope.status2 = 'active';
            break;
        case 'all':
            $scope.statusall = 'active';
            break;
        default :
            $scope.status0 = 'active';
            $stateParams.status = 0;
            break;
    }
    API.getOrderList({
        status:$stateParams.status,
        pagesize : 100
    },function(err,result){
        $scope.orderList = result.data.order_info;
    });
});

function formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
// alert(theTime);
    if(theTime > 60) {
        theTime1 = parseInt(theTime/60);
        theTime = parseInt(theTime%60);
// alert(theTime1+"-"+theTime);
        if(theTime1 > 60) {
            theTime2 = parseInt(theTime1/60);
            theTime1 = parseInt(theTime1%60);
        }
    }
    var result = ""+parseInt(theTime)+"秒";
    if(theTime1 > 0) {
        result = ""+parseInt(theTime1)+"分"+result;
    }
    if(theTime2 > 0) {
        result = ""+parseInt(theTime2)+"小时"+result;
    }
    return result;
}

module.controller('OrderInfoController', function ($scope, API, $stateParams,$ionicPopup,$state,$window,$base64,$interval) {
    $scope.$emit('hideNav',false);
    var order_id = $stateParams.order_id;
    API.orderDetail({order_id:order_id},function(err,result){
        if(result.status == 200){
            // var nowtime = parseInt(Date.parse(new Date()));
            if(result.data.order_info.order_status1 == 0){
                var time_stamp = parseInt(result.data.order_info.time_stamp);
                var s = parseInt(time_stamp/1000);
                if(!s || s == 'NaN') {
                    s = 600;
                }
                var timeout = $interval(function(){
                    $scope.djs = formatSeconds(s)
                    s--;
                },1000,s);
                timeout.then(function(){
                    $state.reload();
                });
            }
            if(result.data.tran_way == 1){
                $scope.tran_way = '自提';
            }else{
                $scope.tran_way = '送货上门';
            }
            result = result.data;
            $scope.order_status = (result.order_info.order_status1 == 0)?true:false;
            $scope.vip_pay_money = (result.order_info.vip_pay_money)?true:false;
            if(result.own_time.indexOf('NaN') >= 0){
                result.own_time = '';
            }
            $scope.order_info = result;
        }else{
            return $state.go('order.index');
        }
    });

    $scope.pay_type = {};
    $scope.pay_type.pay_type = 1;
    $scope.alert = function(msg){
        var confirm = $ionicPopup.confirm({
            title: '选择支付方式',
            template : msg,
            buttons: [
                {
                    text: '<b>确定</b>',
                    type: 'button-positive'
                }
            ]
        });
        confirm.then(function(){
            $state.go('order.index');
        });
    };
    $scope.pay = function(){

        var confirm = $ionicPopup.confirm({
            title: '选择支付方式',
            templateUrl: 'tpl/public/check_pay.html',
            okText : '确定',
            cancelText : '取消',
            scope : $scope
        });
        confirm.then(function(res) {
            if(res) {
                if($scope.pay_type.pay_type){
                    API.checkOrder({
                        order_id : order_id,
                        pay_type : $scope.pay_type.pay_type
                    },function(err,result){
                        if(result.status == 200){
                            if($scope.pay_type.pay_type == 1){
                                var wepay = result.data.wepay;
                                wepay.order_id = order_id;
                                var info = angular.toJson(wepay);
                                $window.location.href='http://www.hjfzqy.cn/#/pay?info='+$base64.encode(info);
                            }else{
                                $state.reload();
                            }
                        }else{
                            $scope.alert(result.message);
                        }
                    });
                }
            }
        });
    };
});


module.controller('OrderSubmitController', function ($scope, API,$ionicModal,addCart,$state,$ionicPopup,$window,$base64) {
    var data = addCart.get();
    addCart.set('');
    if(isEmptyObject(data) ){
        return $state.go('index');
    }
    $scope.order = {};
    $scope.goods_list = data;
    var goods_data = [];
    for(var key in data){
        var goods = {
            goods_id : data[key].goods_id,
            goods_number : data[key].goods_number
        };
        goods_data.push(data[key]);
    }
    API.getStore({id : '57d1177feaff7c6e18c03a0d'},function(err,result){
        $scope.stores = result.data;
        $scope.checked = {};
        $scope.checked.store_address = '请选择提货门店';
    });
    $ionicModal.fromTemplateUrl('tpl/vip/select_store_address.html', {
        scope: $scope,
        animation: 'slide-in-left'
    }).then(function(modal) {
        $scope.store_address_list = modal;
    });
    $scope.open_store_address = function($event){
        $scope.store_address_list.show($event);
    };
    $scope.check_store_address_close = function($event){
        $scope.store_address_list.hide($event);
    };
    $scope.check_store_address = function(info){
        $scope.checked = info;
        for(i in $scope.stores){
            if(info._id == $scope.stores[i]._id){
                $scope.stores[i].checked = true;
            }else{
                $scope.stores[i].checked = false;
            }
        }
        $scope.store_address_list.hide();
    };

    // $scope.$watch('order.date.day', function(newValue) {
    //
    // });
    goods_data = JSON.stringify(goods_data);

    if(!goods_data[0]){
        return $state.go('goods.cart');
    }
    $scope.order.goods_list = goods_data;
    $scope.order.address_type = 1;
    $scope.address_type = {};
    $scope.address_type.address_type_1 = 'active';
    $scope.address_type.address_type_2 = '';
    $scope.$watch('price',function(newVal){
        if(newVal == undefined){
            return false;
        }
        var date=new Date;
        var now_year = date.getFullYear();
        var now_month=date.getMonth()+1;
        var now_day = date.getDate();
        var now_hour = date.getHours();
        // now_hour = 11;
        // now_day = 27;
        var now_min = date.getMinutes();
        var next_month;
        if(parseFloat($scope.price.pay_money) < 300){
            $scope.is_show_address_type = false;
        }else{
            $scope.is_show_address_type = true;
        }
        $scope.price.vip_pay_money = parseFloat($scope.price.pay_money)*parseFloat($scope.vip_discount);
        if(parseFloat($scope.price.pay_money) < 300 || $scope.order.address_type == 2){
            $scope.order.tran_way = 1;
            //门店自提
            $scope.dispatching = 1;
            $scope.mendian = true;
            $scope.songhuo = false;
            $scope.order.date = {};
            $scope.order.date.month = now_month+'月';
            if(now_month == 12){
                next_month = 1;
            }else{
                next_month = now_month + 1;
            }
            $scope.month = [];
            $scope.month[0] = now_month+'月';
            $scope.month[1] = next_month+'月';
            var max_day = DayNumOfMonth(now_year+'年',now_month+'月');
            $scope.day1 = [];
            $scope.day2 = [];
            var a = 0;
            // now_day = 30;
            var next_month_true = true;
            for(var i=now_day;i<=max_day;i++){
                if(a >= 15){
                    next_month_true = false;
                    break;
                }
                $scope.day1[a] = i+'日';
                a++;
            }
            if(!next_month_true){
                $scope.month.pop();
            }else{
                var b = 0;
                for(i=1 ;i<15-a;i++){
                    $scope.day2[b] = i+'日';
                    b++;
                }
            }

            $scope.day = $scope.day1;
            $scope.order.date.day = $scope.day1[0];
            $scope.hour = [];
            if(now_hour < 12){
                $scope.hour[0] = '16:00 - 20:00';
            }else{
                if($scope.day1.length == 1){
                    $scope.day = $scope.day2;
                    $scope.day1 = $scope.day2;
                    $scope.month[0] = $scope.month[1];
                    $scope.month.pop();
                    $scope.order.date.month = $scope.month[0];
                    $scope.order.date.day = $scope.day[0];
                }else{
                    $scope.day1.shift();
                }
                $scope.hour[0] = '10:30 - 20:00';
            }
            $scope.order.date.hour = $scope.hour[0];
            $scope.$watch('order.date.month', function(newValue) {
                if(newValue == $scope.month[0]){
                    $scope.day = $scope.day1;
                    $scope.order.date.day = $scope.day1[0];
                }else{
                    $scope.day = $scope.day2;
                    $scope.order.date.day = $scope.day2[0];
                }
            });

        }else{
            //送货上门
            $scope.order.tran_way = 2;
            $scope.dispatching = 2;
            $scope.songhuo = true;
            $scope.mendian = false;
            $scope.order.date = {};
            $scope.order.date.month = now_month+'月';
            if(now_month == 12){
                next_month = 1;
            }else{
                next_month = now_month + 1;
            }
            $scope.month = [];
            $scope.month[0] = now_month+'月';
            $scope.month[1] = next_month+'月';
            var max_day = DayNumOfMonth(now_year+'年',now_month+'月');
            $scope.day1 = [];
            $scope.day2 = [];
            var a = 0;
            // now_day = 30;
            var next_month_true = true;
            for(var i=now_day;i<=max_day;i++){
                if(a >= 15){
                    next_month_true = false;
                    break;
                }
                $scope.day1[a] = i+'日';
                a++;
            }
            if(!next_month_true){
                $scope.month.pop();
            }else{
                var b = 0;
                for(i=1 ;i<15-a;i++){
                    $scope.day2[b] = i+'日';
                    b++;
                }
            }

            $scope.day = $scope.day1;
            $scope.order.date.day = $scope.day1[0];
            $scope.hour = [];
            if(now_hour < 13){
                var start_time = 10;
                if(now_hour > 10){
                    start_time = now_hour;
                }
                var a = 0;
                start_time = start_time+5;
                for(i = start_time;i<=18;i++){
                    $scope.hour[a] = i + ':00';
                    a++;
                }
                // $scope.hour[0] = '16：00 - 20:00';
            }else{
                if($scope.day1.length == 1){
                    $scope.day = $scope.day2;
                    $scope.day1 = $scope.day2;
                    $scope.month[0] = $scope.month[1];
                    $scope.month.pop();
                    $scope.order.date.month = $scope.month[0];
                    $scope.order.date.day = $scope.day[0];
                }else{
                    $scope.day1.shift();
                }
                start_time = 10;
                var a = 0;
                for(i = start_time;i<=18;i++){
                    $scope.hour[a] = i + ':00';
                    a++;
                }
                // $scope.hour[0] = '10：30 - 20:00';
            }
            $scope.order.date.hour = $scope.hour[0];
            $scope.$watch('order.date.month', function(newValue) {
                if(newValue == $scope.month[0]){
                    $scope.day = $scope.day1;
                    $scope.order.date.day = $scope.day1[0];
                }else{
                    $scope.day = $scope.day2;
                    $scope.order.date.day = $scope.day2[0];
                }
            });
            $scope.$watch('order.date.day', function(newValue) {
                if($scope.order.address_type == 1){
                    if(newValue != now_day+'日'){
                        start_time = 10;
                        var a = 0;
                        for(i = start_time;i<=18;i++){
                            $scope.hour[a] = i + ':00';
                            a++;
                        }
                    }else{
                        var start_time = 10;
                        if(now_hour > 10){
                            start_time = now_hour;
                        }
                        var a = 0;
                        start_time = start_time+5;
                        for(i = start_time;i<=18;i++){
                            $scope.hour[a] = i + ':00';
                            a++;
                        }
                    }
                    $scope.order.date.hour = $scope.hour[0];
                }
            });
        }
    });
    $scope.select_address_type = function(type){
        if(type == 'in'){
            $scope.order.tran_way = 1;
            $scope.address_type.address_type_1 = 'active';
            $scope.address_type.address_type_2 = '';
            $scope.order.address_type = 1;
        }else{
            $scope.order.tran_way = 2;
            $scope.address_type.address_type_1 = '';
            $scope.address_type.address_type_2 = 'active';
            $scope.order.address_type = 2;
        }
    };

    $scope.$watch('order.address_type',function(newVal){
        if(newVal == 1 || newVal == 2){
            API.getPrice({goods_list:goods_data},function(err,result){
                $scope.price = result.data;
                $scope.show_price = result.data;
            });
        }
    });
    API.getPrice({goods_list:goods_data},function(err,result){
        $scope.price = result.data;
        $scope.show_price = result.data;
    });
    API.getDeliveryAddress(function(err,result){
        $scope.user_address = result.data;
    });
    $scope.$watch('user_address',function(result){
        for(var x in result){
            if(result[x].is_default){
                $scope.default_address = result[x];
                $scope.order.address_id = result[x]._id;
            }
        }
        if(!$scope.default_address && result && (result[0])){
            $scope.default_address = result[0];
            $scope.order.address_id = result[0]._id;
        }
        if(!$scope.default_address){
            $scope.default_address = {};
            $scope.default_address.address = '请选择收货地址';
            $scope.order.address_id = '';
        }
    });
    $scope.$watch('order.address_id',function(newadd){
        API.getPrice({
            goods_list : $scope.order.goods_list,
            address_id : newadd
        },function(err,result){
            $scope.price = result.data;
        });
    });
    $scope.$emit('hideNav',false);
    $scope.paytype = {
        wepay : 'active',
        yue : '',
        vip : ''
    };
    $scope.order.pay_type = '1';
    $scope.select_pay = function(action){
        if(action == 'wepay'){
            $scope.paytype.wepay = 'active';
            $scope.paytype.yue = '';
            $scope.paytype.vip = '';
            $scope.order.pay_type = '1';
            $scope.vip_show = false;
        }else if(action == 'yue'){
            $scope.paytype.wepay = '';
            $scope.paytype.yue = 'active';
            $scope.paytype.vip = '';
            $scope.order.pay_type = '2';
            $scope.vip_show = false;
        }else{
            $scope.paytype.wepay = '';
            $scope.paytype.yue = '';
            $scope.paytype.vip = 'active';
            $scope.order.pay_type = '3';
            $scope.price.vip_pay_money = (parseFloat($scope.price.pay_money)*parseFloat($scope.vip_discount)).toFixed(2);
            $scope.vip_show = true;
        }
    };
    $scope.check_address = function(x){
        $scope.default_address = x;
        if(x && x._id){
            $scope.order.address_id = x._id;
        }
        $scope.address_list.hide();
    };
    $scope.add_address_model = {};
    $scope.order.order_type = '1';

    $scope.add_address_model.city = {
        defaultAreaData: ['陕西', '西安','莲湖区'],
        title: '地址:',
        // hardwareBackButtonClose : false,
        // backdrop: true,
        // backdropClickToClose: true,
        // tag: '>>',
        // iconClass: 'ion-location',
    };
    API.getXyctPostal(function(err,result){
        $scope.vip_postal = result.vip_postal;
        $scope.vip_discount = result.vip_discount;
    });
    $scope.add_address_models = {};
    //保存收货地址
    $scope.save_address = function(){
        var city = $scope.add_address_model.city.areaData;
        $scope.add_address_models.province = (city[0])?city[0]:'';
        $scope.add_address_models.city = (city[1])?city[1]:'';
        $scope.add_address_models.area = (city[2])?city[2]:'';
        if($scope.add_address_models.province && !$scope.add_address_models.area){
            $scope.add_address_models.area = $scope.add_address_models.city;
            $scope.add_address_models.city = $scope.add_address_models.province;
        }
        $scope.add_address_models.address_id = ($scope.add_address_models._id)?$scope.add_address_models._id:null;
        API.deliveryAddress($scope.add_address_models,function(err,result){
            if(!err){
                $scope.add_address_models = {};
                $scope.add_address_model.city.areaData = ['陕西', '西安','莲湖区'];
                $scope.address_add.hide();
                $scope.user_address = result.data;
            }
        });
    };
    $scope.delete_address = function(_id){
          API.deleteDeliveryAddress({address_id:_id},function(err,result){
              $scope.user_address = result.data;
          });
    };
    $ionicModal.fromTemplateUrl('tpl/order/address.html', {
        scope: $scope,
        animation: 'slide-in-left'
    }).then(function(modal) {
        $scope.address_list = modal;
    });

    $scope.open_address = function($event){
        $scope.address_list.show($event);
    };

    $scope.check_address_close = function($event){
        $scope.address_list.hide($event);
    };

    $scope.edit_address = function(x){
        // $scope.add_address_model.city = {
        //     defaultAreaData: ['陕西', '西安','莲湖区'],
        //     // title: '地址:'
        // };

        $scope.add_address_models = x;
        $scope.add_address_models.user_name = x.username;
        $scope.add_address_model.city.cityData = [x.province,x.city,x.area];
        $scope.address_add.show();
    };

    //新增地址

    $ionicModal.fromTemplateUrl('tpl/order/address_add.html', {
        scope: $scope,
        animation: 'slide-in-left'
    }).then(function(modal) {
        $scope.address_add = modal;
    });

    $scope.add_address = function(){
        $scope.add_address_model.city.areaData = ['陕西', '西安','莲湖区'];
        $scope.address_add.show();
    };

    $scope.check_address_add_close = function(){
        $scope.address_add.hide();
    };
    API.getPostal(function(err,result){
        $scope.postal = result.money;
        $scope.yue_pay = function() {
            var confirmPopup = $ionicPopup.confirm({
                title: '余额支付',
                template: '您当前的余额为￥'+$scope.postal+'，确认是否支付',
                okText : '确定',
                cancelText : '取消'
            });
            confirmPopup.then(function(res) {
                if(res) {
                    API.setOrder($scope.order,function(err,result){
                        if(result.status == 200){
                            $state.go('order.info',{order_id:result.data.data._id});
                        }else{
                            $scope.errors(result.message);
                        }
                    });
                }
            });
        };
    });
    API.getXyctPostal(function(err,result){
        $scope.vip_postal = result.vip_postal;
        $scope.vip_pay = function() {
            var confirmPopup = $ionicPopup.confirm({
                title: 'VIP支付',
                template: '您当前的VIP卡余额为￥'+$scope.vip_postal+',享受'+ (result.vip_discount*10).toFixed(2)+'折优惠，确认是否支付',
                okText : '确定',
                cancelText : '取消'
            });
            confirmPopup.then(function(res) {
                if(res) {
                    API.setOrder($scope.order,function(err,result){
                        if(result.status == 200){
                            $state.go('order.info',{order_id:result.data.data._id});
                        }else{
                            $scope.errors(result.message);
                        }
                    });
                }
            });
        };
    });

    $scope.cancel = function() {
        var cancels = $ionicPopup.confirm({
            title: '支付失败',
            template: '当前余额不足，请充值后再支付',
            buttons: [
                { text: '<b>确定</b>',
                    type: 'button-positive'
                },
            ]
        });
    };

    $scope.errors = function(msg) {
        var cancels = $ionicPopup.confirm({
            title: '支付失败',
            template: msg,
            buttons: [
                { text: '<b>确定</b>',
                    type: 'button-positive'
                },
            ]
        });
    };

    $scope.cancel2 = function() {
        var cancels = $ionicPopup.confirm({
            title: '支付失败',
            template: '请选择正确的收货地址',
            buttons: [
                { text: '<b>确定</b>',
                    type: 'button-positive'
                },
            ]
        });
    };
    $scope.cancel3 = function() {
        var cancels = $ionicPopup.confirm({
            title: '支付失败',
            template: '请选择自提门店',
            buttons: [
                { text: '<b>确定</b>',
                    type: 'button-positive'
                },
            ]
        });
    };
    $scope.submit = function(){
        if(!$scope.order.address_id){
            return $scope.cancel2();
        }
        if(parseFloat($scope.price.pay_money) < 300 && !$scope.checked._id){
            return $scope.cancel3();
        }
        if($scope.order.address_type == 2 && !$scope.checked._id){
            return $scope.cancel3();
        }
        $scope.order.date = $scope.order.date.month + $scope.order.date.day + ' ' + $scope.order.date.hour;
        if(parseFloat($scope.price.pay_money) < 300 || $scope.order.address_type == 2){
            $scope.order.store = $scope.checked._id;
        }
        switch ($scope.order.pay_type){
            case '1' :
                //微信支付
                API.setOrder($scope.order,function(err,result){
                    var wepay = result.data.wepay;
                    var data = result.data.data;
                    wepay.order_id = data._id;
                    var info = angular.toJson(wepay);
                    window.location.href='http://www.hjfzqy.cn/#/pay?info='+$base64.encode(info);
                });
                break;
            case '2' :
                if(parseFloat($scope.postal) >= parseFloat($scope.price.pay_money)){
                    $scope.yue_pay();
                }else{
                    $scope.cancel();
                }
                break;
            case '3' :
                if(parseFloat($scope.vip_postal) >= ($scope.price.vip_pay_money)){
                    $scope.vip_pay();
                }else{
                    $scope.cancel();
                }
                break;
        }
    };
});



var isEmptyObject = function( obj ) {

    for ( var name in obj ) {
        return false;
    }
    return true;
};





